//
//  LoginViewController.m
//  KurtulusLaw
//
//  Created by phuc phuc on 12/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "FrontViewController.h"
#import "RearViewController.h"
#import "Terms.h"
#import "KurtulusLawController.h"
#import "TermAndCondition.h"
#import "UserService.h"
#import "Constant.h"
#import "PasscodeViewController.h"
#import "AppDelegate.h"
@interface LoginViewController()
{
	BOOL _checkRemember;
}
@end

@implementation LoginViewController 
@synthesize btnRemember;
@synthesize txtUsername;
@synthesize txtPassword;
@synthesize isFristLogin;
@synthesize lbRemember;
@synthesize btnLogin;
@synthesize lb1;
@synthesize lb2;
@synthesize lb3;
@synthesize lb4;
@synthesize lb5;
@synthesize lb0;
@synthesize lb6;

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.txtUsername) {
        [textField resignFirstResponder];
        [self.txtPassword becomeFirstResponder];
    }
    else
    {
        [textField resignFirstResponder];
        [self login:self];
    }
    return YES;
}
#pragma mark - lifecycle
- (id)init {
	self = [super init];
	if (self) {
		
		self.isFristLogin = TRUE;
	}
	
	return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(void) pushToPasscode : (id) sender
{
    PasscodeViewController *passCode = [[PasscodeViewController alloc] init];
	passCode.isCheckPasscode = YES;
    UINavigationController *nav  = [[UINavigationController alloc] initWithRootViewController:passCode];
    [self presentModalViewController:nav animated:YES];
    
}
-(void) checkLoginExist
{
	NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
	NSString *user = [userDefault objectForKey: kKEY_USERNAME];
	NSString *pass = [userDefault objectForKey: kKEY_PASSWORD];
	if ([user length] != 0 && [pass length] != 0) {
		self.txtUsername.text = user;
		self.txtPassword.text = pass;
		[self.btnRemember setImage:[UIImage imageNamed:@"check-box-on-31x32"] forState:UIControlStateNormal];
		[self login:self];
	}
	else
	{
		self.txtUsername.text = @"";
		self.txtPassword.text = @"";
		[self.btnRemember setImage:[UIImage imageNamed:@"check-box-off-31x32"] forState:UIControlStateNormal];
	}
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	_checkRemember = YES;
	[self.btnRemember setImage:[UIImage imageNamed:@"check-box-on-31x32"] forState:UIControlStateNormal];
	self.lb0.backgroundColor = [UIColor clearColor];
	self.lb0.text = NSLocalizedString(@"Law Firm for Business", nil);
	self.txtUsername.placeholder = NSLocalizedString(@"Username / Email", @"");
	self.txtPassword.placeholder = NSLocalizedString(@"Password", @"");
	self.lbRemember.text = NSLocalizedString(@"Remember Login", nil);
	[self.btnLogin setTitle:NSLocalizedString(@"Login", nil) forState:UIControlStateNormal];
	self.lb1.text = NSLocalizedString(@"With Kurtulus & Partners Mob App You Can", nil);
	self.lb2.text = NSLocalizedString(@"View and Download Your Cases and Report", nil);
	self.lb3.text = NSLocalizedString(@"View and Download Your Invoices", nil);
	self.lb4.text = NSLocalizedString(@"View and Download Your Documents", nil);
	self.lb5.text = NSLocalizedString(@"and Video Conference Request", nil);
	self.lb6.text = NSLocalizedString(@"© 2012 Kurtulus Partners, All Rights Reserved", nil);
	
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bgback.png"]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav-bg-black"] forBarMetrics:UIBarMetricsDefault]; 
    
    NSString *sectionTitle = @"KURTULUS";
    
    // Create label with section title
    UILabel *label = [[UILabel alloc] init] ;
    label.frame = CGRectMake(50, 10, 320, 25);
    label.textColor = [UIColor whiteColor];
    label.text = sectionTitle;
    label.backgroundColor = [UIColor clearColor];
    [label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:20.0f]];
    [label sizeToFit];
    
    
    UILabel *label2 =  [[UILabel alloc] init] ;
    label2.frame = CGRectMake(50, 10, 320, 25);
    
    label2.textColor = [UIColor whiteColor];
    label2.backgroundColor = [UIColor clearColor];
    
    [label2 setText:@"&PARTNERS"];
    [label2 setFont:[UIFont fontWithName:@"AppleGothic" size:20.0f]];
    //label.font = [UIFont systemFontOfSize:20.0f];
    [label2 sizeToFit];
    [label2 setFrame:CGRectMake(label.frame.origin.x + label.frame.size.width, label.frame.origin.y, label2.frame.size.width, label2.frame.size.height)];
    [label2 setCenter:CGPointMake(label2.center.x, label.center.y + 1)];
    [self.navigationController.navigationBar addSubview:label];
    
    [self.navigationController.navigationBar addSubview:label2];
	_progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
	
    _progressHUD.dimBackground = YES;
	_progressHUD.labelText = NSLocalizedString(@"Connecting", nil);
	
	[self.view addSubview:_progressHUD];
	
	
	

}
-(void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	if (delegate.isLoginAgain) {
		[self checkLoginExist];
		delegate.isLoginAgain = NO;
	}
}

- (void)viewDidUnload
{
    [self setTxtUsername:nil];
    [self setTxtPassword:nil];
    [self setBtnRemember:nil];
	[self setLbRemember:nil];
    [self setBtnLogin:nil];
	[self setLb1:nil];
	[self setLb2:nil];
	[self setLb3:nil];
	[self setLb4:nil];
	[self setLb5:nil];
    [self setLb0:nil];
    [self setLb6:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)openHomePage:(id)sender {
	FrontViewController *frontViewController = [[FrontViewController alloc] init];
	RearViewController *rearViewController = [[RearViewController alloc] init];
	
	UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:frontViewController];
	
	KurtulusLawController *revealController = [[KurtulusLawController alloc] initWithFrontViewController:navigationController rearViewController:rearViewController];
	UIViewController *view = revealController;
	
	[view setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
	[self presentModalViewController:view animated:YES];
	[revealController revealToggle:nil];
	
}

- (void)createUserDirectory:(NSString *) userID {
	NSString *filePath = [CCommon getUserDirectory];
	NSError *error;	
	
	if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath
                                   withIntermediateDirectories:NO
                                                    attributes:nil
                                                         error:&error])
    {
        NSLog(@"Create directory error: %@", error);
    }

}
- (IBAction)login:(id)sender {
    
	[_progressHUD show:YES];
	[UserService checkLoginWithUserName:self.txtUsername.text pass:self.txtPassword.text :^(id dictionary, NSError *error) {
		if (error) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil) message: [error localizedDescription] delegate:nil cancelButtonTitle: NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
			[alert show];
			[_progressHUD hide:YES];
		}
		else
		{
			@try {
				NSLog(@"%@",dictionary);
				if ([[dictionary objectForKey:@"status"] isEqualToString:@"OK"]) {
					[CCommon setSesionID: [dictionary objectForKey: @"session_id"]];
					[CCommon setUsername:self.txtUsername.text];
					[CCommon setPasword:self.txtPassword.text];
					NSString *userID = [dictionary objectForKey:@"user_id"];
					[CCommon setUserID:userID];
					
					[self createUserDirectory:userID];
					
					NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
					if (_checkRemember) {
						[userDefault setObject:self.txtUsername.text forKey: kKEY_USERNAME];
						[userDefault setObject:self.txtPassword.text forKey: kKEY_PASSWORD];
						[userDefault synchronize];
						
					}
					[_progressHUD hide:YES];
					
					if (isFristLogin) {
						if (![CCommon checkPasscode])
						{
							BOOL checkTerm = [[userDefault objectForKey:@"checkterm"] boolValue];
							if (checkTerm) {
								[self openHomePage:self];
							}
							else
							{
								TermAndCondition *term = [[TermAndCondition alloc] init];
								[self presentModalViewController:term animated:NO];
							}
							
						}
						else
						{
							[self pushToPasscode:self];
						}
						
						
					} else {
						[self.navigationController popViewControllerAnimated:YES];
					}
					//self.txtUsername.text = @"";
					//self.txtPassword.text = @"";
					
				}
				else
				{
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Sorry, you have entered incorrect login credentials", nil) message: NSLocalizedString(@"Please check your entries and try again", nil) delegate:nil cancelButtonTitle: NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
					[alert show];
					[_progressHUD hide:YES];
				}
			}
			@catch (NSException *exception) {
				[_progressHUD hide:YES];
			}
			@finally {
				//
			}
			
		}
	}];
	
	
}

- (IBAction)openWeb:(id)sender {
    NSURL *url = [ [ NSURL alloc ] initWithString: kURL_BASE ];
    
    [[UIApplication sharedApplication] openURL:url];
}

- (IBAction)hideKeyboard:(id)sender {
    [self.txtPassword resignFirstResponder];
    [self.txtUsername resignFirstResponder];
}

- (IBAction)openTerm:(id)sender {
    Terms *terms = [[Terms alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:terms];
    [self presentModalViewController:nav animated:NO];
    
}

- (IBAction)checkRemember:(id)sender {
	if (_checkRemember) {
		[self.btnRemember setImage:[UIImage imageNamed:@"check-box-off-31x32"] forState:UIControlStateNormal];
		_checkRemember = NO;
	}
	else
	{
		[self.btnRemember setImage:[UIImage imageNamed:@"check-box-on-31x32"] forState:UIControlStateNormal];
		_checkRemember = YES;
	}
}


@end
